//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, {
	PureComponent,
	Fragment
} from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
import ExportJsonExcel from 'js-export-excel';
import {
	Row,
	Col,
	Card,
	Form,
	Input,
	Select,
	Icon,
	Button,
	Modal,
	message,
	Divider,
	Table,
	DatePicker,
	Popconfirm
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import SelectPoliceRankTree from '@/components/SelectPoliceRankTree';
import SelectChangeTypeTree from '@/components/SelectChangeTypeTree';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import ProUserCreateForm from './ProUserCreateForm';//新增表单
import ProUserUpdateForm from './ProUserUpdateForm';//修改表单
import ProUserViewForm from './ProUserViewForm';//查看表单

import styles from './ProUserList.less';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;
const { RangePicker } = DatePicker;
//用户列表

class StandardTable extends PureComponent {

  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
          scroll={{x: 'max-content'}}
        />
      </div>
    );
  }
}


const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {

	constructor(props) {
	    super(props);

	    this.state = {
	    	editing: false,
		    modalByInfoItem: false,
		    infoItemValue: props.record?props.record.info_item:null,
	    };
  	}
  	//信息项弹窗
  	handleModalByInfoItem = flag => {
		this.setState({
			modalByInfoItem: !!flag,
		});
	};

	//获取信息项
	getInfoItem = val => {
		console.log(val);
		this.setState({
			infoItemValue: val
		})
	};

  toggleEdit = () => {
    const editing = !this.state.editing;
    this.setState({ editing }, () => {
      if (editing) {
      	if(this.input) {
      		this.input.focus();
      	}else if(this.select){
      		this.select.focus();
      	}
      }
    });
  };

  save = e => {
    const { record, handleSave } = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({ ...record, ...values });
    });
  };

  renderCell = form => {
  	const { infoItemValue } = this.state;
    this.form = form;
    const { children, dataIndex, record, title } = this.props;
    const { editing } = this.state;
    let serviceReeStr;
    if(editing && dataIndex == "left_paren") {
    	serviceReeStr = (
    		<Form.Item style={{ margin: 0 }}>
	      		{form.getFieldDecorator(dataIndex, {
		          rules: [
		            {
		              required: false,
		              message: `${title} is required.`,
		            },
		          ],
		          initialValue: record[dataIndex],
			    })(<Select ref={node => (this.select = node)} style={{ width: '100%' }} placeholder="请选择" onBlur={this.save}>
				      <Option value="(">(</Option>
				      <Option value="((">((</Option>
				      <Option value="(((">(((</Option>
				      <Option value="((((">((((</Option>
				      <Option value="(((((">(((((</Option>
				   </Select>)
			    }
	      </Form.Item>
    	)
    }else if(dataIndex == "info_item"){
    	serviceReeStr = (
        <div style={{width: '100%',height: '20px',lineHeight: '20px'}} onClick={()=> this.handleModalByInfoItem(true)}>{infoItemValue}</div>
    	)
    }else if(editing && dataIndex == "relation"){
    	serviceReeStr = (
    		<Form.Item style={{ margin: 0 }}>
	      		{form.getFieldDecorator(dataIndex, {
		          rules: [
		            {
		              required: false,
		              message: `${title} is required.`,
		            },
		          ],
		          initialValue: record[dataIndex],
			    })(
			    	<Select ref={node => (this.select = node)} style={{ width: '100px' }} placeholder="请选择" onBlur={this.save}>
				      <Option value="=">等于</Option>
				      <Option value="<=">小于等于</Option>
				      <Option value="<">小于</Option>
				      <Option value="like">包含</Option>
				      <Option value="is null">非空</Option>
				      <Option value=">=">大于等于</Option>
				      <Option value=">">大于</Option>
				      <Option value="<>">不等于</Option>
				   </Select>
			    )}
	      </Form.Item>
    	)
    }else if(editing && dataIndex == "query_value"){
    	serviceReeStr = (
    		<Form.Item style={{ margin: 0 }}>
	      		{form.getFieldDecorator(dataIndex, {
		          rules: [
		            {
		              required: false,
		              message: `${title} is required.`,
		            },
		          ],
		          initialValue: record[dataIndex],
			    })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save} />)}
	      </Form.Item>
    	)
    }else if(editing && dataIndex == "right_paren"){
    	serviceReeStr = (
    		<Form.Item style={{ margin: 0 }}>
	      		{form.getFieldDecorator(dataIndex, {
		          rules: [
		            {
		              required: false,
		              message: `${title} is required.`,
		            },
		          ],
		          initialValue: record[dataIndex],
			    })(
			    	<Select ref={node => (this.select = node)} style={{ width: '100%' }} placeholder="请选择" onBlur={this.save}>
				      <Option value=")">)</Option>
				      <Option value="))">))</Option>
				      <Option value=")))">)))</Option>
				      <Option value="))))">))))</Option>
				      <Option value=")))))">)))))</Option>
				   </Select>
			    )}
	      </Form.Item>
    	)
    }else if(editing && dataIndex == "logical_symbol"){
    	serviceReeStr = (
    		<Form.Item style={{ margin: 0 }}>
	      		{form.getFieldDecorator(dataIndex, {
		          rules: [
		            {
		              required: false,
		              message: `${title} is required.`,
		            },
		          ],
		          initialValue: record[dataIndex],
			    })(
			    	<Select ref={node => (this.select = node)} style={{ width: '100%' }} placeholder="请选择" onBlur={this.save}>
				      <Option value="且">且</Option>
				      <Option value="或">或</Option>
				   </Select>
			    )}
	      </Form.Item>
    	)
    }else {
    	serviceReeStr = (
	    	<div
		        className="editable-cell-value-wrap"
		        style={{ width: '100%',height: '20px' }}
		        onClick={this.toggleEdit}
		      >
	        	{children}
	      	</div>
    	)
    }
    return (
    	<div>{serviceReeStr}</div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    const parentMethods = {
    	getInfoItem: this.getInfoItem,
    	handleModalByInfoItem: this.handleModalByInfoItem
    }
    const { modalByInfoItem } = this.state;
    return (
		<td {...restProps}>
			<Modal
			width={800}
			centered
			destroyOnClose
			title="信息项"
			visible={modalByInfoItem}
			onCancel={() => this.handleModalByInfoItem(false)}
			footer={null}
			>
			<InfoItemTable {...parentMethods}/>
			</Modal>
	        {editable ? (
	          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
	        ) : (
	          children
	        )}
	    </td>
    );
  }
}

//查询条件设置
class SetConditionTable extends React.Component {
  constructor(props) {
    super(props);
    console.log(props);
    this.columns = [
      {
        title: '左括号',
        dataIndex: 'left_paren',
        editable: true,
      },
      {
        title: '信息项',
        dataIndex: 'info_item',
        editable: true,
      },
      {
        title: '关系',
        dataIndex: 'relation',
        editable: true,
      },
      {
        title: '查询值',
        dataIndex: 'query_value',
        editable: true,
      },
      {
        title: '右括号',
        dataIndex: 'right_paren',
        editable: true,
      },
      {
        title: '逻辑符',
        dataIndex: 'logical_symbol',
        editable: true,
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        width: '180px',
        render: (text, record,index) =>
          this.state.dataSource.length >= 1 ? (
          	<Fragment>
          	<a onClick={()=>this.handleUpMove(text,record,index)}>上移</a>
          	<Divider type="vertical" />
          	<a onClick={()=>this.handleDownMove(text,record,index)}>下移</a>
          	<Divider type="vertical" />
          	<a onClick={()=>this.handleInsert(text,record,index)}>插入</a>
          	<Divider type="vertical" />
            <Popconfirm title="确定删除此项吗?" onConfirm={() => this.handleDelete(record.key)}>
              <a>删除</a>
            </Popconfirm>
            </Fragment>
          ) : null,
      },
    ];

    this.state = {
      dataSource: [
        {
          key: '0',
          left_paren: '(',
          info_item: '现授衔称',
          relation: '=',
          query_value: '未授衔',
          right_paren: ')',
          logical_symbol: '且',
        },
        {
          key: '1',
          left_paren: '(',
          info_item: '现任职务层次',
          relation: '=',
          query_value: '省部级正职',
          right_paren: ')',
          logical_symbol: '且',
        },
      ],
      count: 2,
      selectedRows: [],
      checkflag: false
    };
  }

    setClassName = (record, index) => {
    	const { checkflag } = this.state;
      return ( index == 3 && checkflag ? styles.staffTableRow : '')
    }

    onSelectChange = (selectedRowKeys,selectedRows) => {
      this.setState({ selectedRows });
    };

  //导入excel
  	onImportExcel = file => {
  	    // 获取上传的文件对象
  	    const { files } = file.target;
  	    const { dispatch } = this.props;
        const { dataSource,count } = this.state;
        let _this = this;
  	    // 通过FileReader对象读取文件
  	    const fileReader = new FileReader();
  	    fileReader.onload = event => {
  	        try {
  				const { result } = event.target;
  	            // 以二进制流方式读取得到整份excel表格对象
  	            const workbook = XLSX.read(result, { type: 'binary' });
  	            // 存储获取到的数据
  	            let data = [];
  	            // 遍历每张工作表进行读取（这里默认只读取第一张表）
  	            for (const sheet in workbook.Sheets) {
  		            // esline-disable-next-line
  		            if (workbook.Sheets.hasOwnProperty(sheet)) {
  		                // 利用 sheet_to_json 方法将 excel 转成 json 数据
  		                data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
  		                // break; // 如果只取第一张表，就取消注释这行
  		            }
  		        }
            const newData = [
              {
                key: count,
                left_paren: '(',
                info_item: '任职时间',
                relation: '=',
                query_value: '5',
                right_paren: ')',
                logical_symbol: '且',
              },
              {
                key: count + 1,
                left_paren: '(',
                info_item: '警衔起算时间',
                relation: '=',
                query_value: '2019',
                right_paren: ')',
                logical_symbol: '或',
              },
            ]

            _this.setState({
              dataSource: [...dataSource, ...newData],
              checkflag: false
            });

  		        message.success('导入成功！');
  	        } catch (e) {
  	            // 这里可以抛出文件类型错误不正确的相关提示
  	            message.error('文件类型不正确！');
  	        }
  	    };
  	    // 以二进制方式打开文件
  	    fileReader.readAsBinaryString(files[0]);
  	}

  //导出excel
  downloadExl = () => {
  	const { selectedRows } = this.state;
  	if(!selectedRows.length) {
  		Modal.warning({
  		    title: '请选择需要导出的查询条件',
  		    okText: '确认',
  		    centered: true,
  		});
  		return false;
  	}
    	var option={};
    	let dataTable = [];
    	if(selectedRows) {
      	for(let i in selectedRows) {
        		if(selectedRows){
  	        	let obj = {
  		          '左括号': selectedRows[i].left_paren,
  		          '信息项': selectedRows[i].info_item,
  		          '关系': selectedRows[i].relation,
  		          '查询值': selectedRows[i].query_value,
  		          '右括号': selectedRows[i].right_paren,
                '逻辑符': selectedRows[i].logical_symbol,
  		        }
          		dataTable.push(obj);
        		}
      	}
    	}
  	  option.fileName = '查询条件'
  	  option.datas=[
  	    {
  	      sheetData:dataTable,
  	      sheetName:'查询条件',
  	      sheetHeader:['左括号','信息项','关系','查询值','右括号','逻辑符'],
  	      columnWidths: [10,10,10,10,10,10],
  	      columnHeights: [10,10,10,10,10,10]
  	    }
  	  ];

  	  var toExcel = new ExportJsonExcel(option);
  	  toExcel.saveExcel();
  }

  //校验查询条件
  checkQueryItem = () => {
  	const { selectedRows } = this.state;
  	if(!selectedRows.length) {
  		Modal.warning({
  		    title: '请选择需要校验的查询条件',
  		    okText: '确认',
  		    centered: true,
  		});
  		return false;
  	}
    if(selectedRows.length < 5) {
      message.success('校验成功');
    }else {
      message.error('存在校验失败条件');
    }
    this.setState({ checkflag: true });
  }

  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter(item => item.key !== key),checkflag: false });
  };


  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: 32,
      address: `London, Park Lane no. ${count}`,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      checkflag: false
    });
  };

  handleInsert = (text,record,index) => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      name: `Edward King ${count}`,
      age: 32,
      address: `London, Park Lane no. ${count}`,
    };
    if(dataSource) {
    	dataSource.splice(index+1,0,newData)
    }
    this.setState({
      dataSource: [...dataSource],
      count: count + 1,
      checkflag: false
    });
  };

  swapArray = (arr, index1, index2) => {
	   arr[index1] = arr.splice(index2, 1, arr[index1])[0];
	   return arr;
  }

  zIndexDown = (arr,index,length) => {
	   if(index+1 != length){
	       this.swapArray(arr, index, index+1);
	   }else{
	      alert('已经处于置底，无法下移');
	  }
  }

  zIndexUp = (arr,index,length) => {
	   if(index != 0){
	       this.swapArray(arr, index, index - 1);
	   }else{
	      alert('已经处于置顶，无法上移');
	  }
  }

  //下移
  handleDownMove = (text,record,index) => {
    const { count, dataSource } = this.state;
	this.zIndexDown(dataSource,index,dataSource.length);
    this.setState({
      dataSource: [...dataSource],
      count,
    });
  };

  //上移
  handleUpMove = (text,record,index) => {
    const { count, dataSource } = this.state;
	this.zIndexUp(dataSource,index,dataSource.length);
    this.setState({
      dataSource: [...dataSource],
      count,
    });
  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
  };

  handleSubmit = () => {

  };

  render() {
    const { dataSource,selectedRows } = this.state;
    const rowSelection = {
      selectedRows,
      onChange: this.onSelectChange,
    };
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return (
      <div className={styles.setCondition}>
        <Button onClick={this.handleAdd} type="primary" style={{ marginBottom: 16 }}>
          添加
        </Button>
        <Button onClick={this.downloadExl} type="primary" style={{ marginBottom: 16,float: 'right' }}>
          导出
        </Button>

        <Button type="primary" style={{ marginBottom: 16,float: 'right',marginRight: '10px' }}>
            <Input className={styles.file_uploader} type='file' accept='.xlsx, .xls' onChange={this.onImportExcel}/>
            导入
        </Button>
        <Button onClick={this.checkQueryItem} type="primary" style={{ marginBottom: 16,float: 'right',marginRight: '10px'   }}>
          校验
        </Button>
        <Table
          rowSelection={rowSelection}
          components={components}
          rowClassName={this.setClassName}
          bordered
          dataSource={dataSource}
          columns={columns}
          size="middle"
        />
      </div>
    );
  }
}

//查看查询条件
class ViewConditionTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '左括号',
        dataIndex: 'left_paren',
        editable: true,
      },
      {
        title: '信息项',
        dataIndex: 'info_item',
        editable: true,
      },
      {
        title: '关系',
        dataIndex: 'relation',
        editable: true,
      },
      {
        title: '查询值',
        dataIndex: 'query_value',
        editable: true,
      },
      {
        title: '右括号',
        dataIndex: 'right_paren',
        editable: true,
      },
      {
        title: '逻辑符',
        dataIndex: 'logical_symbol',
        editable: true,
      },
    ];

    this.state = {
      dataSource: [
        {
          key: '0',
          left_paren: '',
          info_item: '现授衔称',
          relation: '=',
          query_value: '未授衔',
          right_paren: '',
          logical_symbol: '',
        },
        {
          key: '1',
          left_paren: '',
          info_item: '现任职务层次',
          relation: '=',
          query_value: '省部级正职',
          right_paren: '',
          logical_symbol: '',
        },
      ],
      count: 2,
    };
  }

  render() {
    const { dataSource } = this.state;

    return (
      <div className={styles.setCondition}>
        <Table
          bordered
          dataSource={dataSource}
          columns={this.columns}
          size="middle"
        />
      </div>
    );
  }
}

@connect(({
	standardset,
	loading
}) => ({
	standardset,
	loading: loading.models.standardset,
}))

//信息项
class InfoItemTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '字段名称',
        dataIndex: 'field_name',
      },
      {
        title: '描述',
        dataIndex: 'describe',
      },
      {
        title: '字段类型',
        dataIndex: 'field_type',
      },
      {
        title: '长度',
        dataIndex: 'field_length',
      },
      {
        title: '代码',
        dataIndex: 'code',
      },
    ];

    this.state = {
      selectedRowKeys: [],
    };
  }

  	componentDidMount() {
		const { dispatch } = this.props;
		dispatch({
			type: 'standardset/query_page_for_infoitem',
		});
	}

  onSelectChange = (selectedRowKeys,selectedRows) => {
  	const { getInfoItem,handleModalByInfoItem } = this.props;
  	getInfoItem(selectedRows[0].describe);
  	handleModalByInfoItem();
    this.setState({ selectedRowKeys });
  };

  render() {
  	console.log(this.props);
  	if(!this.props.standardset.dataForInfoItem) return;
  	const {
  		standardset: {
  			dataForInfoItem: {list}
  		}
  	} = this.props;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className={styles.setCondition}>
        <Table
          bordered
          rowSelection={rowSelection}
          dataSource={list}
          columns={this.columns}
          size="middle"
        />
      </div>
    );
  }
}

/* eslint react/no-multi-comp:0 */

@connect(({
	standardset,
	loading
}) => ({
	standardset,
	loading: loading.models.standardset,
}))
@Form.create()
class ProStaffSelectList extends PureComponent {
	state = {
		modalVisible: false,
		updateModalVisible: false,
		viewModalVisible: false,
		expandForm: false,
		selectedRows: [],
		formValues: {},
		updateFormValues: {},
		viewFormValues: {},
		requestModelName:"standardset",
		currentPage: 1,
		pageSize: 10,

		modalBySetCondition: false,
		modalByViewSetCondition: false,
    resetFlag: false,
	};


	columns = [
        {
	        title: '类别',
	        dataIndex: 'change_type',
	        key: 'change_type',
        }, 	{
	        title: '名称',
	        dataIndex: 'name',
	        key: 'name',
        },  {
	        title: '变动后警衔',
	        dataIndex: 'changepolicerank',
	        key: 'changepolicerank',
        },  {
	        title: '更新时间',
	        dataIndex: 'updatetime',
	        key: 'updatetime',
        },  {
			title: '操作',
			fixed:'right',
			align: 'center',
    		width: 160,
			render: (text, record) => {
	        	const { updateButtonVisible,deleteButtonVisible } = this.state;
	        	return (
		        	<Fragment>
		        		<a onClick={() => this.handleModalBySetCondition(true, record)} style={{display: 'inline-block',padding: '5px 0'}}>设置条件</a>
						{/*<Divider type="vertical" />
						<a onClick={() => this.handleModalByViewSetCondition(true, record)}>查看条件</a>
					    <a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
					    <Divider type="vertical" />
					    <a onClick={() => this.handleDeleteRecord(record)}>删除</a>
						<Divider type="vertical" />
						<Button  type="primary"  icon="edit"  style={{marginRight: '5px'}} onClick={() => this.handleUpdateModalVisible(true, record)}></Button>
						<Divider type="vertical" />
						<Button  type="danger" icon="delete" onClick={() => this.handleDeleteRecord(record)}></Button>*/}

				    </Fragment>
	        	);

			}
		},
	];

	componentDidMount() {
		const { dispatch } = this.props;
		dispatch({
			type: 'standardset/query_page_for_standardset',
		});
	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const { dispatch } = this.props;
		const { formValues } = this.state;

		this.setState({
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			selectedRows: [],
		})

		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});

		const params = {
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			...formValues,
			...filters,
		};
		if(sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}

		dispatch({
			type: 'standardset/query_page_for_standardset',
			payload: params,
		});
	};

	previewItem = id => {
		router.push(`/profile/basic/${id}`);
	};

	handleFormReset = () => {
		const { form,dispatch } = this.props;
		form.resetFields();
		this.setState({
				formValues: {},
				currentPage:1,
				selectedRows: [],
        resetFlag: true,
		});
		dispatch({
			type: 'standardset/query_page_for_standardset',
		});
	};

	toggleForm = () => {
		const { expandForm } = this.state;
		this.setState({
			expandForm: !expandForm,
		});
	};


	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};

	handleSearch = e => {
		e.preventDefault();

		const {
			dispatch,
			form
		} = this.props;

		form.validateFields((err, fieldsValue) => {
			if(err) return;


      const { getPoliceRankTreeBySelectTree,getChangeTypeTreeBySelectTree } = this.state;
      if (getPoliceRankTreeBySelectTree) {
        fieldsValue.changepolicerank = getPoliceRankTreeBySelectTree.triggerNode.props.dataRef.title;
      }

      if (getChangeTypeTreeBySelectTree) {
        fieldsValue.change_type = getChangeTypeTreeBySelectTree.triggerNode.props.dataRef.title;
      }

			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};

			this.setState({
				currentPage:1,
				selectedRows: [],
				formValues: values,
        resetFlag: false,
			});

			dispatch({
				type: 'standardset/query_page_for_standardset',
				payload: values,
			});
		});
	};

	handleModalVisible = flag => {
		this.setState({
			modalVisible: !!flag,
		});
	};

	handleUpdateModalVisible = (flag, record) => {
		this.setState({
			updateModalVisible: !!flag,
			updateFormValues: record || {},
		});
	};

	handleViewModalVisible = (flag, record) => {
		this.setState({
			viewModalVisible: !!flag,
			viewFormValues: record || {},
		});
	};

	handleAdd = fields => {
		const { dispatch } = this.props;

		dispatch({
			type: 'prouser/insert_for_prouser',
			payload: {
				user_name: fields.user_name,
				user_name_cn: fields.user_name_cn,
				password: fields.password,
				email: fields.email,
				phone: fields.phone,
				auth_ids: fields.auth_ids,
				dept_id: fields.dept_id,
				dept: fields.dept,
				post_id: fields.post_id,
				post_name: fields.post_name,
				enabled: fields.enabled,

				is_system_user: fields.is_system_user,
				creator_id: fields.creator_id,
				inner_dept_code: fields.inner_dept_code,
				org_code: fields.org_code,
				org: fields.org,
				inner_org_code: fields.inner_org_code,
				memos: fields.memos,
				avatar: fields.avatar,
				job: fields.job,
				createTime: fields.createTime,
			},
			callback:(res) => {
	        	if(res.success) {
					message.success('添加成功');
	        	}else {
        			message.success('添加失败');
	        	}
  			}
		});

		this.setState({
				selectedRows: [],
		});

		this.handleModalVisible();

	};


	handleUpdate = fields => {

		const { dispatch } = this.props;
		const { currentPage,pageSize } = this.state;
		dispatch({
			type: 'prouser/update_for_prouser',
			payload: {
				user_id: fields.user_id,
				user_name: fields.user_name,
				user_name_cn: fields.user_name_cn,
				password: fields.password,
				email: fields.email,
				phone: fields.phone,
				auth_ids: fields.auth_ids,
				dept_id: fields.dept_id,
				dept: fields.dept,
				post_id: fields.post_id,
				post_name: fields.post_name,
				enabled: fields.enabled,
				currentPage,
        		pageSize
			},
			callback:(res) => {
	        	if(res.success) {
					message.success('修改成功');
	        	}else {
        			message.success('修改失败');
	        	}
      		}
		});

		this.setState({
			selectedRows: [],
		});

		this.handleUpdateModalVisible();

	};

	handleDeleteRecord = record => {
		const { dispatch } = this.props;
		const { currentPage,pageSize } = this.state;
		confirm({
	    title: '您确定要删除此项吗?',
	    okText: '确认',
	    cancelText: '取消',
	    onOk() {

	    },
	    onCancel() {},
	  });

	  this.setState({
			selectedRows: [],
	   });

	};
	//拟授警衔
	selectedPoliceRankTreeValue = (deptRecord) => {
		  this.setState({
  			getPoliceRankTreeBySelectTree: deptRecord,
  		})
	}

	//职务层次
	selectedDutyLevelTreeValue = (deptRecord) => {
		  this.setState({
  			getDutyLevelTreeBySelectTree: deptRecord,
  		})
	}

	//单位
	selectedWorkTreeValue = (deptRecord) => {
		  this.setState({
  			getWorkTreeBySelectTree: deptRecord,
  		})
	}

	//变动类型
	selectedChangeTypeTreeValue = (deptRecord) => {
		  this.setState({
  			getChangeTypeTreeBySelectTree: deptRecord,
  		})
	}

	renderSimpleForm() {
		const {
			form: {
				getFieldDecorator
			},
			standardset: {
				selectPoliceRankTree,
				selectChangeTypeTree
			},
		} = this.props;
		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
      resetFlag: this.state.resetFlag
		}
		const parentChangeTypeTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedChangeTypeTreeValue: this.selectedChangeTypeTreeValue,
			selectChangeTypeTree,
      resetFlag: this.state.resetFlag
		}
		return(
        <Form onSubmit={this.handleSearch} layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col md={8} sm={24}>
                <FormItem label="拟授警衔">
                  {getFieldDecorator('changepolicerank')(<SelectPoliceRankTree  {...parentPoliceRankTreeMethod}/>)}
                </FormItem>
            </Col>
            <Col md={8} sm={24}>
                <FormItem label="变动类型">
                  {getFieldDecorator('change_type')(<SelectChangeTypeTree  {...parentChangeTypeTreeMethod}/>)}
                </FormItem>
            </Col>
            <Col md={8} sm={24}>
                <span className={styles.submitButtons}>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  展开 <Icon type="down" />
                </a>
                </span>
              </Col>
            </Row>
        </Form>
		);
	}

	renderAdvancedForm() {
		const {
			form: {
				getFieldDecorator
			},
			standardset: {
				selectPoliceRankTree,
				selectChangeTypeTree
			},
		} = this.props;
		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
      resetFlag: this.state.resetFlag
		}
		const parentChangeTypeTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedChangeTypeTreeValue: this.selectedChangeTypeTreeValue,
			selectChangeTypeTree,
      resetFlag: this.state.resetFlag
		}
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				      <Col md={8} sm={24}>
					        <FormItem label="拟授警衔">
					        	{getFieldDecorator('changepolicerank')(<SelectPoliceRankTree  {...parentPoliceRankTreeMethod}/>)}
							</FormItem>
				    	</Col>
			      		<Col md={8} sm={24}>
					        <FormItem label="变动类型">
					        	{getFieldDecorator('change_type')(<SelectChangeTypeTree  {...parentChangeTypeTreeMethod}/>)}
							</FormItem>
				    	</Col>
				    	<Col md={8} sm={24}>
					        <FormItem label="创建时间">
						        {getFieldDecorator('starttime')(

						        	<RangePicker format={"YYYY-MM-DD"} style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />

						        )}
					    	</FormItem>
					    </Col>
		    	</Row>
			    <div style={{ overflow: 'hidden' }}>
					<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        收起 <Icon type="up" />
			        </a>
		        	</div>
		        </div>
        </Form>
		);
	}

	renderForm() {
		const {
			expandForm
		} = this.state;

		return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
	}
	//查询条件设置弹窗
	handleModalBySetCondition = flag => {
		this.setState({
			modalBySetCondition: !!flag,
		});
	};
	//保存查询条件设置
	handleModalBySave = () => {
		this.handleModalBySetCondition();
    message.success('设置成功');
	}
	//查询条件查看弹窗
	handleModalByViewSetCondition = flag => {
		this.setState({
			modalByViewSetCondition: !!flag,
		});
	};
	render() {
		const {
			standardset: {
				data,
				authForUser,
				postForUser
			},
			loading,
		} = this.props;

		const {
			selectedRows,
			modalVisible,
			updateModalVisible,
			viewModalVisible,
			updateFormValues,
			viewFormValues,
			addButtonVisible,

			modalBySetCondition,
			modalByViewSetCondition,
		} = this.state;

		const parentMethods = {
			handleAdd: this.handleAdd,
			handleModalVisible: this.handleModalVisible,
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			authForUser,
			postForUser
		};
		const updateMethods = {
			handleUpdateModalVisible: this.handleUpdateModalVisible,
			handleUpdate: this.handleUpdate,
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			authForUser,
			postForUser
		};
		const viewMethods = {
			handleViewModalVisible: this.handleViewModalVisible
		};
		return(
			<PageHeaderWrapper title="警衔标准设置列表">
			<Modal
				width={800}
				centered
				title="设置查询条件"
				visible={modalBySetCondition}
				onOk={()=> this.handleModalBySave()}
				onCancel={()=> this.handleModalBySetCondition()}
				>
				<SetConditionTable />
			</Modal>
			<Modal
				width={800}
				centered
				destroyOnClose
				title="查询条件"
				visible={modalByViewSetCondition}
				onOk={()=> this.handleModalByViewSetCondition()}
				onCancel={()=> this.handleModalByViewSetCondition()}
				>
				<ViewConditionTable />
			</Modal>
            <Card bordered={false}>
            <div className={styles.proUsertableList}>
            <div className={styles.proUsertableListForm}>{this.renderForm()}</div>
            <div className={styles.proUsertableListOperator}>
        	{/*<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
    		新增
    		</Button>*/}
    	</div>
        <StandardTable
        rowKey={"user_id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>

        <ProUserCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <ProUserUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <ProUserViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
		);
	}
}

export default ProStaffSelectList;
